import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 加载Iris数据集，选择Setosa和Versicolor
data = load_iris()
X = data.data[:100]  # 只选择Setosa和Versicolor
y = data.target[:100]

# 数据标准化
scaler = StandardScaler()
X = scaler.fit_transform(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 构建弱分类器函数
def weak_classifier(X, feature_index, threshold):
    return np.where(X[:, feature_index] >= threshold, 1, -1)

# 选择M个弱分类器
M = 10  # 假设构建10个弱分类器
classifiers = []
accuracies = []

# 构造多个弱分类器
for i in range(M):
    feature_index = i % 4  # 随机选择特征
    threshold = np.random.uniform(np.min(X_train[:, feature_index]), 
                                 np.max(X_train[:, feature_index]))  # 随机设定阈值
    classifiers.append((feature_index, threshold))  # 存储每个弱分类器的特征索引和阈值
    
    # 计算每个弱分类器的准确率
    predictions = weak_classifier(X_train, feature_index, threshold)
    accuracy = np.sum(predictions == y_train) / len(y_train)
    accuracies.append(accuracy)

# 输出每个弱分类器的准确率
for j, acc in enumerate(accuracies):
    print(f"弱分类器{j+1}准确率: {acc:.4f}")